import { unref, type Ref, onUnmounted, onDeactivated, isRef, watch } from 'vue'
import { onMountedOrActivated } from './onMountedOrActivated'

type TargetRef = EventTarget | Ref<EventTarget>
export type UseEventListenerOptions = {
  target?: TargetRef
  capture?: boolean
  passive?: boolean
}
export const useEventListener = <K extends keyof DocumentEventMap>(
  type: K,
  listener: EventListener | any,
  options: UseEventListenerOptions = {}
) => {
  const { target = window, capture = false, passive = false } = options
  const add = (target: EventTarget) => {
    // 拿到初始dom
    const element = unref(target)
    if (element) {
      element.addEventListener(type, listener, {
        passive,
        capture
      })
    }
  }

  const remove = (target: EventTarget) => {
    const element = unref(target)
    if (element) {
      element.removeEventListener(type, listener, capture)
    }
  }
  onMountedOrActivated(() => add(target as EventTarget))
  onUnmounted(() => remove(target as EventTarget))
  onDeactivated(() => remove(target as EventTarget))

  if (isRef(target)) {
    watch(target, (newVal: TargetRef, oldVal: TargetRef) => {
      remove(oldVal as EventTarget)
      add(newVal as EventTarget)
    })
  }
}
